# -*- coding:utf-8 -*-
"""
# @File : middleware.py
# @Author:chen
# @Date : 2023/10/10
# @Desc :
"""

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
from django.conf import settings
import re


class RBACMiddleware(MiddlewareMixin):
    def process_request(self,request):
        #判断当前请求的url是否在权限列表中
        #1. 获取当前请求的url
        # current_url = request.path_info
        current_url = request.path
        # print(current_url)
        # print('*'* 90)
        # 2. 判断当前访问的url在不在白名单中
        for url in getattr(settings,'WHITE_URLS',[]):
            if re.match(r'^{}$'.format(url),current_url):
                #如果在白名单的url直接放行
                return
        # 判断当前这次请求的url在不在权限列表中
        key = getattr(settings,'PERMISSION_SESSION_KEY','permission_list')
        # 3 当前登录的这个人他的权限列表获取， 获取session中的数据

        permission_list = request.session.get(key,[])
        # print(permission_list)
        # print('*'*120)
        # 4. 因为django url存在模糊匹配，所以校验权限的时候也要用正则取匹配
        for pattern in permission_list:
            if re.match(r'^{}$'.format(pattern),current_url):
                # 有权限放行
                return None
        else:
            return HttpResponse('没有权限！')































